#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
from PyQt6.QtWidgets import QApplication, QMessageBox, QSplashScreen
from PyQt6.QtGui import QPixmap, QIcon
from PyQt6.QtCore import Qt, QTimer

from ui.main_window import MainWindow
from core.image_processor import ImageProcessor

def excepthook(exc_type, exc_value, exc_traceback):
    """全局异常处理函数"""
    tb = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
    print(f"发生异常:\n{tb}")
    QMessageBox.critical(
        None, 
        "程序错误", 
        f"程序发生错误:\n{exc_value}"
    )

def main():
    # 创建应用程序
    app = QApplication(sys.argv)
    app.setStyle('Fusion')  # 使用Fusion风格，在所有平台上都能获得一致的外观
    
    # 设置应用程序图标
    icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "icon.png")
    if os.path.exists(icon_path):
        app.setWindowIcon(QIcon(icon_path))
    
    # 创建启动画面
    splash_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "splash.png")
    splash = None
    if os.path.exists(splash_path):
        splash_pixmap = QPixmap(splash_path)
        splash = QSplashScreen(splash_pixmap)
        splash.show()
        app.processEvents()
    
    # 初始化图像处理器
    try:
        # 创建图像处理器
        image_processor = ImageProcessor()
        
        # 检查模型是否可用
        if not image_processor.is_model_available():
            if splash:
                splash.close()
            
            # 显示警告消息
            QMessageBox.warning(
                None,
                "模型未安装",
                "Waifu2x-Caffe 模型文件未找到。请确保已将模型文件放置在models/waifu2x-caffe目录下。\n"
                "应用程序仍将运行，但处理功能将不可用。"
            )
    
    except Exception as e:
        if splash:
            splash.close()
        
        # 显示错误消息
        QMessageBox.critical(
            None,
            "初始化错误",
            f"应用程序初始化失败: {str(e)}"
        )
        return 1
    
    # 创建并显示主窗口
    try:
        window = MainWindow(image_processor)
        
        # 延迟关闭启动画面，确保主窗口已准备好
        if splash:
            QTimer.singleShot(1000, splash.close)
        
        window.show()
        return app.exec()
    
    except Exception as e:
        if splash:
            splash.close()
        
        # 显示错误消息
        QMessageBox.critical(
            None,
            "初始化错误",
            f"无法创建应用程序主窗口: {str(e)}"
        )
        return 1

if __name__ == "__main__":
    sys.excepthook = excepthook
    sys.exit(main())
